﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CodeDynamiksEngine;

namespace codedynamiks_mes_baguio
{
    public partial class frmInventoryItemDialog : Form
    {
        DataCache items = new DataCache("ITEMS");
        string desc = "", stockNum = "";
        bool hasRecord = false;

        public frmInventoryItemDialog()
        {
            InitDialog();
        }
        public frmInventoryItemDialog(string stockNumber, string description, string unit, float qty, float estimatecost)
        {
            InitDialog();
            stockNum = stockNumber;
            desc = description;

            txtSearch.Text = desc;
            txtUnit.Text = unit;
            txtQty.Value = (decimal)qty;
            txtCost.Value = (decimal)estimatecost;

            if (stockNum != "")
            {
                Enable(false);
                PRSearch();
            }
        }
        private void InitDialog()
        {
            InitializeComponent();
            Enable(false);
            LoadUnits();
            GUIEvents();
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
        private void Enable(bool b)
        {
            pnlMain.Enabled = b;
            pnlWait.Visible = !b;
        }
        private void GUIEvents()
        {
            txtSearch.KeyPress += new KeyPressEventHandler(delegate(object s, KeyPressEventArgs e)
            {
                if (e.KeyChar == (char)13)
                {
                    Enable(false);
                    PRSearch();
                }
            });
            btnOk.Click += new EventHandler(delegate
            {
                if (txtMonth.SelectedIndex == -1)
                {
                    Confirm.Generic("Add Item", "Please specify a month.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                if ((int)txtQty.Value == 0)
                {
                    Confirm.Generic("Add Item", "Please specify a quantity.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                if (!hasRecord)
                {
                    if (txtCost.Value == 0m)
                    {
                        Confirm.Generic("Add Item", "Please specify an estimated cost.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    if (txtUnit.Text.Trim() == "")
                    {
                        Confirm.Generic("Add Item", "Please specify a unit.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    desc = txtSearch.Text;
                    stockNum = "";
                }

                DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            });
            btnCancel.Click += new EventHandler(delegate
            {
                DialogResult = System.Windows.Forms.DialogResult.Cancel;
                this.Close();
            });
            grdSearch.SelectionChanged += new EventHandler(delegate
            {
                if (grdSearch.SelectedRows.Count == 0)
                {
                    hasRecord = false;
                    return;
                }
                hasRecord = true;
                int ind = grdSearch.SelectedRows[0].Index;
                desc = items.GetValue(ind, "Description").ToString();
                stockNum = items.GetValue(ind, "Stock No.").ToString();
                txtCost.Value = decimal.Parse(items.GetValue(ind, "Estimated Cost").ToString());
                txtUnit.Text = items.GetValue(ind, "Unit").ToString();
            });
        }
        private void FormatGrid_ItemSearch()
        {
            foreach (DataGridViewColumn dvc in grdSearch.Columns)
            {
                if (dvc.ValueType == typeof(float))
                {
                    dvc.DefaultCellStyle.Format = "#,#0.00";
                    dvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                }
            }
        }
        private void LoadUnits()
        {
             CodeScript s = new CodeScript("LOAD");
            s.Add(CodeIns.DBU_NEW_CORE);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRV"), Common.CFG.Read("DB"),
                   Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SVR"));
            s.Add(CodeIns.DBU_QUERY, "SELECT fData FROM tbllookup WHERE fKey='UNIT' ORDER BY fData ASC");
            s.Add(CodeIns.DBU_END);

            CodeProcessor c = new CodeProcessor();
            c.ProcessCompleted += new EventHandler(delegate
            {
                c.SafeCall(this, delegate
                {
                    if (c.State == ProcessorFlag.DataRdyErr ||
                           c.State == ProcessorFlag.Error ||
                           c.State == ProcessorFlag.ReadyErr)
                    {
                        Confirm.Error("Initialize Units", "Cannot initialize choices due to the error :\r\n" + c.GetProcessorMessage);
                        this.Close();
                        return;
                    }
                    DataCache d;
                    c.DataFetch(out d);
                    d.SetActivePage(0);
                    txtUnit.Items.Clear();
                    txtUnit.Items.AddRange(d.GetObjectList(0));
                    Enable(true);
                });
            });
            c.Run(s);
        }
        private void PRSearch()
        {
            CodeScript s = new CodeScript("SEARCH");
            s.Add(CodeIns.DBU_NEW_CORE);
            s.Add(CodeIns.DBU_CONNECT, Common.CFG.Read("DRV"), Common.CFG.Read("DB"),
                   Common.CFG.Read("UID"), Common.CFG.Read("PWD"), Common.CFG.Read("SVR"));
            s.Add(CodeIns.DBU_BEGIN_TRANSACTION);
            s.Add(CodeIns.DBU_QUERY, string.Format("SELECT fStockNum AS 'Stock No.', fDescription AS 'Description', " +
                "fType AS 'Type', fArticle AS 'Article', fUnit AS 'Unit' , fEstimatedCost AS 'Estimated Cost', fStatus AS 'Status' " +
                "FROM tbl_ip_itemrecord WHERE  " +
                "fStockNum LIKE '%{0}%' OR " +
                "fDescription LIKE '%{0}%' OR " +
                "fType LIKE '%{0}%' OR " +
                "fArticle LIKE '%{0}%' OR " +
                "fUnit LIKE '%{0}%' OR " +
                "fEstimatedCost LIKE '%{0}%' OR " +
                "fStatus LIKE '%{0}%' " +
                "ORDER BY fType ASC, fUnit ASC, fDescription ASC", txtSearch.Text)
                );
            s.Add(CodeIns.DBU_END);
            CodeProcessor c = new CodeProcessor();
            c.ProcessCompleted += new EventHandler(delegate
            {
                c.SafeCall(this, delegate
                {
                    if (c.State == ProcessorFlag.DataRdyErr ||
                           c.State == ProcessorFlag.Error ||
                           c.State == ProcessorFlag.ReadyErr)
                    {
                        Confirm.Error("Search", "Cannot perform search due to the error :\r\n" + c.GetProcessorMessage);
                        Enable(true);
                        return;
                    }
                    c.DataFetch(out items);

                    items.SetActivePage(0);
                    grdSearch.DataSource = items.ExportPage();

                    FormatGrid_ItemSearch();
                    Enable(true);

                    if (items.GetRecordCount(0) == 0) txtSearch.Focus();
                });
            });
            c.Run(s);
        }

        //Data Functions
        public string StockNumber
        {
            get { return stockNum; }
        }
        public string Description
        {
            get { return desc.Trim().ToUpper(); }
        }
        public string Unit
        {
            get { return txtUnit.Text.Trim().ToUpper(); }
        }
        public float Qty
        {
            get { return (float)txtQty.Value; }
        }
        public float EstimateCost
        {
            get { return (float)txtCost.Value; }
        }
        public string Month
        {
            get { return txtMonth.Text; }
        }
    }
}
